import 'package:campus_vision/routes/app_router.dart';
import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
import 'package:flutter_riverpod/flutter_riverpod.dart';
import 'package:flutter_svg/flutter_svg.dart';
import 'package:go_router/go_router.dart';

import '../providers/auth_provider.dart';

class LoginPage extends ConsumerStatefulWidget {
  const LoginPage({super.key});

  @override
  ConsumerState<LoginPage> createState() => _LoginPageState();
}

class _LoginPageState extends ConsumerState<LoginPage> {
  final usernameController = TextEditingController();
  final passwordController = TextEditingController();

  @override
  void initState() {
    super.initState();
    usernameController.text = "admin";
    passwordController.text = "password";
  }

  @override
  Widget build(BuildContext context) {
    final authState = ref.watch(authStateProvider);
    return AnnotatedRegion<SystemUiOverlayStyle>(
      value: const SystemUiOverlayStyle(
        statusBarColor: Colors.transparent,
        statusBarBrightness: Brightness.light,
        statusBarIconBrightness: Brightness.dark,
        systemNavigationBarIconBrightness: Brightness.dark,
      ),
      child: Scaffold(
        body: Center(
          child: SingleChildScrollView(
            padding: const EdgeInsets.all(24.0),
            child: Form(
              key: GlobalKey<FormState>(),
              child: Column(
                mainAxisAlignment: MainAxisAlignment.center,
                crossAxisAlignment: CrossAxisAlignment.stretch,
                children: [
                  SvgPicture.asset(
                    'assets/images/logo.svg',
                    height: 100,
                    width: 100,
                    fit: BoxFit.contain,
                    placeholderBuilder: (context) =>
                        const CircularProgressIndicator(),
                  ),
                  const SizedBox(height: 24),
                  const Text(
                    '校视通',
                    textAlign: TextAlign.center,
                    style: TextStyle(
                      fontSize: 28,
                      fontWeight: FontWeight.bold,
                    ),
                  ),
                  const SizedBox(height: 48),
                  // 用户名
                  CupertinoTextField(
                    controller: usernameController,
                    placeholder: '用户名',
                    prefix: const Padding(
                      padding: EdgeInsets.only(left: 10),
                      child: Icon(CupertinoIcons.person,
                          color: CupertinoColors.systemGrey),
                    ),
                    padding: const EdgeInsets.symmetric(
                        vertical: 16, horizontal: 10),
                    decoration: BoxDecoration(
                      border: Border.all(color: CupertinoColors.systemGrey4),
                      borderRadius: BorderRadius.circular(8),
                    ),
                  ),
                  const SizedBox(height: 16),

                  // 密码
                  CupertinoTextField(
                    controller: passwordController,
                    placeholder: '密码',
                    prefix: const Padding(
                      padding: EdgeInsets.only(left: 10),
                      child: Icon(CupertinoIcons.lock,
                          color: CupertinoColors.systemGrey),
                    ),
                    padding: const EdgeInsets.symmetric(
                        vertical: 16, horizontal: 10),
                    decoration: BoxDecoration(
                      border: Border.all(color: CupertinoColors.systemGrey4),
                      borderRadius: BorderRadius.circular(8),
                    ),
                    obscureText: true,
                  ),
                  const SizedBox(height: 24),

                  // 错误信息
                  if (authState.hasError) ...[
                    Text(
                      authState.error.toString(),
                      style: const TextStyle(color: Colors.red),
                      textAlign: TextAlign.center,
                    ),
                    const SizedBox(height: 24),
                  ],
                  // 登录按钮
                  CupertinoButton.filled(
                    onPressed:
                        authState.isLoading ? null : () => _login(context, ref),
                    padding: const EdgeInsets.symmetric(vertical: 16),
                    child: authState.isLoading
                        ? const CupertinoActivityIndicator(
                            color: CupertinoColors.white)
                        : const Text(
                            '登录',
                            style: TextStyle(fontSize: 18),
                          ),
                  ),
                ],
              ),
            ),
          ),
        ),
      ),
    );
  }

  Future<void> _login(BuildContext context, WidgetRef ref) async {
    // 简单验证（你也可以加 Form 验证）
    if (usernameController.text.isEmpty || passwordController.text.isEmpty) {
      _showToast(context, "请输入用户名或、密码");
      return;
    }

    // 触发登录
    await ref.read(authStateProvider.notifier).login(
          usernameController.text,
          passwordController.text,
        );

    final auth = ref.read(authStateProvider).value;
    if (auth != null) {
      if (context.mounted) {
        context.replace(AppRoute.home);
      }
    }
  }

  void _showToast(BuildContext context, String message) {
    final snackBar = SnackBar(
      content: Text(
        message,
        textAlign: TextAlign.center,
        style: const TextStyle(
          color: Colors.white,
          fontSize: 16,
        ),
      ),
      behavior: SnackBarBehavior.floating, // 浮动模式（不遮挡底部导航）
      duration: const Duration(seconds: 2),
    );

    ScaffoldMessenger.of(context).showSnackBar(snackBar);
  }
}
